﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using CustomVirtualizingPanel;

namespace VirtualizingPanelDemo
{
    /// <summary>
    /// Interaction logic for VirtualizingPagerPanelWindow.xaml
    /// </summary>
    public partial class VirtualizingPagerPanelWindow : Window
    {
        private const int ADD_CHILDREN_COUNT = 5000;   // 子元素添加个数
        private VirtualizingPagerPanel _pagerPanel;

        public VirtualizingPagerPanelWindow()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(VirtualizingPagerPanelWindowLoaded);
        }

        private void VirtualizingPagerPanelWindowLoaded(object sender, RoutedEventArgs e)
        {
            if (_pagerPanel == null)
            {
                VirtualizingItemsControl.ApplyTemplate();
                var presenter = (ItemsPresenter)VirtualizingItemsControl.Template.FindName("PART_ItemsPresenter", VirtualizingItemsControl);
                _pagerPanel = (VirtualizingPagerPanel)VirtualizingItemsControl.ItemsPanel.FindName("PART_PagerPanel", presenter);

                // 设置分页控件绑定
                var pageSizeBind = new Binding("PageSize") { Source = _pagerPanel, Mode = BindingMode.OneWay };
                ResourcePager.SetBinding(ResourcePager.PageSizeProperty, pageSizeBind);
                var itemCountBind = new Binding("ChildrenCount") { Source = _pagerPanel, Mode = BindingMode.OneWay };
                ResourcePager.SetBinding(ResourcePager.TotalItemsCountProperty, itemCountBind);

                // 设置分页容器绑定
                var pageIndexBind = new Binding("PageIndex") { Source = ResourcePager, Mode = BindingMode.OneWay };
                _pagerPanel.SetBinding(VirtualizingPagerPanel.PageIndexProperty, pageIndexBind);
            }
        }

        private void SetNormalItemsControlItemSource(object sender, RoutedEventArgs e)
        {
            ((Button)sender).Visibility = Visibility.Collapsed;

            var dataSource = new List<int>();
            for (int i = 0; i < ADD_CHILDREN_COUNT; i++)
            {
                dataSource.Add(i);
            }

            NormalItemsControl.ItemsSource = dataSource;
        }

        private void SetVirtualizingItemsControlItemSource(object sender, RoutedEventArgs e)
        {
            ((Button)sender).Visibility = Visibility.Collapsed;

            var dataSource = new List<int>();
            for (int i = 0; i < ADD_CHILDREN_COUNT; i++)
            {
                dataSource.Add(i);
            }

            VirtualizingItemsControl.ItemsSource = dataSource;
        }
    }
}
